package com.guang.alicloud.nacos.consumer.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Controller("sentinel")
@Slf4j
public class SentinelHelloController {

    @PostConstruct
    public void init() {
        List<FlowRule> flowRules = new ArrayList<>();
        //创建流控规则对象
        FlowRule flowRule = new FlowRule();
        //设置流控规则 QPS
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //设置受保护的资源
        flowRule.setResource("HelloSentinel");
        //设置受保护的资源的阈值
        flowRule.setCount(1);
        flowRules.add(flowRule);
        //加载配置好的规则
        FlowRuleManager.loadRules(flowRules);
    }


    @RequestMapping("/helloSentinelV1")
    public String testHelloSentinelV1() {
        Entry entity = null;
        try {
            entity = SphU.entry("helloSentinelV1");
            //开始执行 自己的业务方法
            //结束执行自己的业务方法
        } catch (BlockException e) {
            log.info("testHelloSentinelV1方法被流控了");
            return "testHelloSentinelV1方法被流控了";
        } finally {
            if (entity != null) {
                entity.exit();
            }
        }
        return "";
    }
}
